package com.example.mycontacts;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
	
	public static final String USER_ID = "userid";
	public static final String PHONE = "phone";
	public static final String ALTPHONE = "altphone";
	public static final String EMAIL = "email";
	public static final String COMMENTS = "comments";
	public static final String NAME = "name";
	
	public static final String CITY = "city";
	public static final String STATE = "state";
	public static final String ADDRESS = "address";
	public static final String ZIPCODE = "zipcode";
	
	public static final String CATEGORIES = "categories";
	public static final String CATEGORY   ="cat";
	
	public static final String TAG = "DBAdapter";
	
	private static final String DATABASE_NAME = "newcontacts";
	private static final String DATABASE_TABLE_ONE = "information";
	private static final String DATABASE_TABLE_THREE = "categories";
	private static final int DATABASE_VERSION = 1;
	
	private static final String DATABASE_CREATE =  "CREATE TABLE information( userid INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, "+
			"phone TEXT, altphone TEXT, email TEXT, comments TEXT, address TEXT, cat TEXT, "+
			"FOREIGN KEY(cat) REFERENCES categories(categories));";
	
	private static final String CATEGORY_DATABASE_CREATE = "CREATE TABLE categories ( categories TEXT PRIMARY KEY);";
			
	
	private final Context context;
	private DatabaseHelper DBHelper;
	private SQLiteDatabase db;
	
	
	public DBAdapter(Context ctx){
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
	}
	
	
	
	//DatabaseHelper class 
	private static class DatabaseHelper extends SQLiteOpenHelper {
		
		DatabaseHelper(Context context){
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}
		
		@Override
		public void onCreate(SQLiteDatabase db){
			db.execSQL(CATEGORY_DATABASE_CREATE);
			db.execSQL(DATABASE_CREATE);
			
			try{
			ContentValues initialValues = new ContentValues();
			initialValues.put("categories", "None");
			db.insert(DATABASE_TABLE_THREE, null, initialValues);
			for(int i = 1; i < 6; i++){
				initialValues.put("categories", "Category " + i);
				db.insert(DATABASE_TABLE_THREE, null, initialValues);
			}
			}catch (RuntimeException e){
				Log.e("OnCrteadddsdgfsd", e.toString(), e);
			}			

		}
		
		// in this method of upgrading, we just drop the table and recreate it (assuming all data will be lost)
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
			Log.w(TAG, "Upgrading database from version " + oldVersion +
		          " to" + newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS titles"); 
			onCreate(db);
		}
		
	}//end of DaabaseHelper class
	
	
	
	
	//Opens the database
	public void open() throws SQLException {
		db = DBHelper.getWritableDatabase();
		
	}
	
	//Closes the database
	public void close(){
		//will close the database
		DBHelper.close();
	}	
	
	public long insertInformation(Information info, Address addr) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(NAME, info.getName());
		initialValues.put(PHONE, info.getPhoneNumber());
		initialValues.put(ALTPHONE, info.getAltPhone());
		initialValues.put(EMAIL, info.getEmailAddress());
		initialValues.put(COMMENTS, info.getComments());
		String str = addr.getStreetAddress() + "~|~" + addr.getCity() + "~|~ " + addr.getState() + "~|~" + addr.getZipcode() + "~|~";
		initialValues.put(ADDRESS, str);
		initialValues.put(CATEGORY, info.getCategory());
		
		//returns the Row id of the new added row, or -1 if an error occurs
		return db.insert(DATABASE_TABLE_ONE, null, initialValues);
	}
	
public ArrayList<String> getCats(){
		
		ArrayList<String> cats = new ArrayList<String>();
		String sql = "SELECT categories FROM categories;";
		try {
		Cursor cursor = db.rawQuery(sql, null);
			
		
		if(cursor.moveToFirst()) {
			do {
				cats.add(cursor.getString(0));
				cursor.moveToNext();
			}while(!cursor.isAfterLast());
		}
		cursor.close();
		
	    }catch (RuntimeException e) {
	    	Log.e("DataBassGetCats", e.toString(), e);
	    }
			return cats;
		}
	
	
	//will need to modify, name can be the same for users
	public boolean deleteContact(String name){
		return db.delete(DATABASE_TABLE_ONE, NAME + "=" + name, null) >0;
	}


	
	public List<Information> searchContacts(String query){
		
		List<Information> infoList = new ArrayList<Information>();
		Information info;
		
		String sql = "SELECT * FROM information WHERE name LIKE '%" + query + "%' ORDER BY name;";
		Cursor cursor = db.rawQuery(sql, new String[] {});
		try{	
		
		if(cursor.moveToFirst())
		{
		
		do
		{
			info = new Information();
			info.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));
			info.setName(cursor.getString(cursor.getColumnIndex(NAME)));
			info.setPhoneNumber(cursor.getString(cursor.getColumnIndex(PHONE)));
			info.setAltPhone(cursor.getString(cursor.getColumnIndex(ALTPHONE)));
			info.setEmailAddress(cursor.getString(cursor.getColumnIndex(EMAIL)));
			info.setComments(cursor.getString(cursor.getColumnIndex(COMMENTS)));
			infoList.add(info);
			cursor.moveToNext();
		}while(!cursor.isAfterLast());
		}

	} catch (RuntimeException e)
    {
		cursor.close();
		Log.e("DataBassCat", e.toString(), e);
	}
		cursor.close();
		return infoList;
	}
	
	
	public List<Information> populateContactsListView(){
		
		
		List<Information> infoList = new ArrayList<Information>();
		Information info;
		String sql = "SELECT * FROM information ORDER BY name;"; //ORDER BY name;";
		Cursor cursor = db.rawQuery(sql, new String[] {});
		try{
			
		
		if(cursor.moveToFirst())
		{
		
		
		do
		{
			info = new Information();
			info.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));
			info.setName(cursor.getString(cursor.getColumnIndex(NAME)));
			infoList.add(info);
			cursor.moveToNext();
		}while(!cursor.isAfterLast());
		}
		

	} catch (RuntimeException e)
    {
		cursor.close();
		Log.e("DataBassPop", e.toString(), e);
	}
		cursor.close();
		return infoList;
	}
	
	public Cursor populateContacts()
	{
		String[] str = {NAME};
		return db.query(DATABASE_TABLE_ONE, str, null, null, null, null,"name");
	}
	
	public Information getInformation(int userid)
	{
		Information info = new Information();
		
			String sql = "SELECT * FROM information WHERE userid = " + userid;
			Cursor cursor = db.rawQuery(sql, null);
			cursor.moveToFirst();
				info.setName(cursor.getString(cursor.getColumnIndex(NAME)));
				info.setPhoneNumber(cursor.getString(cursor.getColumnIndex(PHONE)));
				info.setAddress(cursor.getString(cursor.getColumnIndex(ADDRESS)));
				info.setAltPhone(cursor.getString(cursor.getColumnIndex(ALTPHONE)));
				info.setEmailAddress(cursor.getString(cursor.getColumnIndex(EMAIL)));
				info.setComments(cursor.getString(cursor.getColumnIndex(COMMENTS)));
				info.setCategory(cursor.getString(cursor.getColumnIndex(CATEGORY)));
				
		cursor.close();
		db.close();
		return info;
	}


	public long updateContact(Information info, Address addr, String userid){
		ContentValues content = new ContentValues();
		content.put(NAME, info.getName());
		content.put(PHONE, info.getPhoneNumber());
		content.put(ALTPHONE, info.getAltPhone());
		content.put(EMAIL, info.getEmailAddress());
		content.put(COMMENTS, info.getComments());
		content.put(CATEGORY, info.getCategory());
		String str = addr.getStreetAddress() + "~|~" + addr.getCity() + "~|~ " + addr.getState() + "~|~" + addr.getZipcode() + "~|~";
		content.put(ADDRESS, str);
		
		return db.update(DATABASE_TABLE_ONE, content, USER_ID + "=" +userid, null);
	}
	
	public long deleteInformation(String userid)
	{
		return db.delete(DATABASE_TABLE_ONE, USER_ID + "=" + userid, null);
		
	}
	
public List<Information> populateCategoryListView(String catName){
		
		
		List<Information> infoList = new ArrayList<Information>();
		Information info;
		String sql = "SELECT * FROM information WHERE cat = '" + catName + "' ORDER BY name;"; //ORDER BY name;";
		Cursor cursor = db.rawQuery(sql, new String[] {});
		try{
			
		
		if(cursor.moveToFirst())
		{
		
		
		do
		{
			info = new Information();
			info.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));
			info.setName(cursor.getString(cursor.getColumnIndex(NAME)));
			infoList.add(info);
			cursor.moveToNext();
		}while(!cursor.isAfterLast());
		}
		

	} catch (RuntimeException e)
    {
		cursor.close();
		Log.e("DataBassCatPop", e.toString(), e);
	}
		cursor.close();
		return infoList;
	}

public void changeCategory(String old, String newStr)
{
	System.out.println("1");
	 ContentValues content = new ContentValues();
	 ContentValues initial = new ContentValues();
	 System.out.println("2");

	 content.put(CATEGORY, newStr);
	 initial.put(CATEGORIES, newStr);

	 String WHERE = String.format("%s='%s'", CATEGORIES, old);
	 db.update(DATABASE_TABLE_THREE, initial, WHERE, null);
	 WHERE =String.format("%s='%s'", CATEGORY, old);
   db.update(DATABASE_TABLE_ONE, content, WHERE, null);
	  
   }

}
